package com.easyxu.kubernetes.filebrowser.adpter.web.controller;

import com.easyxu.kubernetes.filebrowser.service.KubernetesService;
import com.easyxu.kubernetes.filebrowser.service.dto.DirectoryQryCmd;
import com.easyxu.kubernetes.filebrowser.service.dto.FileDownloadCmd;
import com.easyxu.kubernetes.filebrowser.service.dto.data.DirectoryDto;
import io.kubernetes.client.openapi.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

@Controller
@RequestMapping("/kubernetes")
public class KubernetesController {

    @Autowired
    private KubernetesService kubernetesService;

    @GetMapping("/namespaces")
    public ResponseEntity<List<String>> allNamespace(){
        return ResponseEntity.ok(kubernetesService.getAllNamespace());
    }

    @GetMapping("/deployments")
    public ResponseEntity<List<String>> deployments(@RequestParam String namespace){
        return ResponseEntity.ok(kubernetesService.getDeploymentByNamespace(namespace));
    }

    @GetMapping("/pods")
    public ResponseEntity<List<String>> pods(@RequestParam String namespace,@RequestParam String deployment) throws ApiException {
        return ResponseEntity.ok(kubernetesService.getPodByNamespaceAndDeployment(namespace, deployment));
    }

    @GetMapping("/filebrowser")
    public ResponseEntity<List<DirectoryDto>> filebrowser(DirectoryQryCmd cmd) throws IOException, ApiException {
        return ResponseEntity.ok(kubernetesService.filebrowser(cmd));
    }

    @GetMapping("/download")
    public void download(FileDownloadCmd cmd, HttpServletResponse response) throws IOException, ApiException {
        InputStream inputStream = kubernetesService.getPodFileStream(cmd);

        String fileName = cmd.getFilePath().substring(cmd.getFilePath().lastIndexOf("/") + 1);

        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        try(BufferedInputStream bis = new BufferedInputStream(inputStream)) {
            byte[] buff = new byte[1024];
            OutputStream os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        }
    }
}
